import { defineStore } from 'pinia'
import {
  addCartAPI,
  getCartListAPI,
  deleteCartAPI,
  updateCartAPI,
  selectAllAPI,
} from '@/services/cart'
import type { CartItem } from '@/types/cart'
import { ref, computed } from 'vue'

export const useCartStore = defineStore('cart', () => {
  /** 购物车列表 */
  const cartList = ref<CartItem[]>([])

  /**购物车商品总量 */
  const cartTotal = computed(() => {
    return cartList.value.reduce((total, item) => total + +item.count, 0)
  })

  /** 购物车商品总价 */
  const cartTotalPrice = computed(() => {
    return cartList.value.reduce((total, item) => total + +item.nowPrice * item.count, 0).toFixed(2)
  })

  /**是否全选 */
  const isAllChecked = computed(() => {
    return cartList.value.every((item) => item.selected)
  })

  /** 选中商品列表 */
  const selectedList = computed(() => {
    return cartList.value.filter((item) => item.selected)
  })

  /**选中商品总价 */
  const selectedTotalPrice = computed(() => {
    return selectedList.value
      .reduce((total, item) => total + +item.nowPrice * item.count, 0)
      .toFixed(2)
  })

  /**加入购物车
   * @param { string } skuId sku id
   * @param { number } count 数量
   */
  const addCart = async (skuId: string, count: number) => {
    const res = await addCartAPI(skuId, count)
    return res
  }

  /**获取购物车列表 */
  const getCartList = async () => {
    const res = await getCartListAPI()
    cartList.value = res.result
  }

  /**删除商品 */
  const deleteCart = async (ids: string[]) => {
    const res = await deleteCartAPI(ids)
    return res
  }

  /**
   * 修改购物车单品
   * @param { string } skuId SKU ID
   * @param { object } data  selected 选中状态 count 商品数量
   */
  const updateCart = async (skuId: string, data: { selected?: boolean; count?: number }) => {
    const res = await updateCartAPI(skuId, data)
    return res
  }

  /**
   * 购物车全选/反选
   * @param { boolean } selected 是否选中
   */
  const changeAllChecked = async (selected: boolean) => {
    const res = await selectAllAPI(selected)
    return res
  }

  /**
   * 仓库购物车全选/反选 —— 解决极短时间内反复点击全选/反选按钮导致反复发送请求（先改变本地再发送请求）
   * @param { boolean } selected
   */
  const changeAllCheckedInLocal = async (selected: boolean) => {
    cartList.value.forEach((item) => {
      item.selected = selected
    })
  }

  return {
    cartList,
    cartTotal,
    cartTotalPrice,
    isAllChecked,
    selectedList,
    selectedTotalPrice,
    addCart,
    getCartList,
    deleteCart,
    updateCart,
    changeAllChecked,
    changeAllCheckedInLocal,
  }
})
